package model

import (
	"fmt"

	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ OutlayModel = (*customOutlayModel)(nil)
var (
	cacheOutlayRidPrefix = "cache:outlay:rid:"
)

type (
	// OutlayModel is an interface to be customized, add more methods here,
	// and implement the added methods in customOutlayModel.
	OutlayModel interface {
		outlayModel
		FindOneByRid(rid int64) (*Outlay, error)
	}

	customOutlayModel struct {
		*defaultOutlayModel
	}
)

// NewOutlayModel returns a model for the database table.
func NewOutlayModel(conn sqlx.SqlConn, c cache.CacheConf) OutlayModel {
	return &customOutlayModel{
		defaultOutlayModel: newOutlayModel(conn, c),
	}
}

func (m *defaultOutlayModel) FindOneByRid(rid int64) (*Outlay, error) {
	outlayRidKey := fmt.Sprintf("%s%v", cacheOutlayRidPrefix, rid)
	//相符、一致、重叠、同时发生
	var coincide Outlay
	err := m.QueryRow(&coincide, outlayRidKey, func(conn sqlx.SqlConn, v interface{}) error {
		//例行公事
		ritual := fmt.Sprintf("select %s from %s where `rid` =  ? limit 1", outlayRows, m.table)
		return conn.QueryRow(v, ritual, rid)
	})
	switch err {
	case nil:
		return &coincide, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}
